﻿using Architecture.API.Application.Command.UserInfoCommand;
using Architecture.API.Extension;
using Architecture.Domain;
using Architecture.Domain.Dto.UserInfoDto;
using Architecture.Domain.Service.RoleServices;
using Architecture.Domain.Service.UserInfoServices;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.Data;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace Architecture.API.Controllers
{
    /// <summary>
    /// API控制器--用户管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    //[Authorize]
    public class UserManagemementController : ControllerBase
    {
        /// <summary>
        /// 用户信息服务
        /// </summary>
        protected readonly IUserInfoService _userInfoService;

        /// <summary>
        /// 日志
        /// </summary>
        protected readonly ILogger<UserManagemementController> logger;

        /// <summary>
        /// 命令总线
        /// </summary>
        protected readonly IMediator _mediator;

        /// <summary>
        /// 配置
        /// </summary>
        protected readonly IConfiguration configuration;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userInfoService">用户信息服务</param>
        /// <param name="logger">日志</param>
        /// <param name="mediator">命令总线</param>
        /// <param name="configuration">配置</param>
        public UserManagemementController(IUserInfoService userInfoService, ILogger<UserManagemementController> logger, IMediator mediator, IConfiguration configuration)
        {
            _userInfoService = userInfoService;
            this.logger = logger;
            _mediator = mediator;
            this.configuration = configuration;
        }

        /// <summary>
        /// 添加用户信息
        /// </summary>
        /// <param name="userInfo">用户信息</param>
        /// <returns>返回受影响的行数</returns>
        [HttpPost]
        public async Task<ApiResult<int>> AddUser(UserInfo userInfo)
        {
            ApiResult<int> result = new ApiResult<int>();

            try
            {
                var res = await _userInfoService.GetAllAsync(userName: userInfo.UserName);
                if (res.Count > 0)
                {
                    result.Code = -2;
                }
                else
                {
                    result.Data = await _userInfoService.AddAsync(userInfo);
                }
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }

        ///// <summary>
        ///// 获取全部用户列表
        ///// </summary>
        ///// <returns>返回全部用户列表</returns>
        //[HttpGet]
        //public async Task<ApiResult<object>> GetUserList()
        //{
        //    //string str = "123";

        //    //int res = str.ToInt();

        //    //string birth = "412722200103144017";

        //    //string idCart = birth.Substring(6, 8);

        //    //string birthday = birth.GetBirthday();

        //    ApiResult<object> result = new ApiResult<object>();
        //    try
        //    {
        //        result.Data = await _userInfoService.GetALLInfoAsync();
        //    }
        //    catch (Exception ex)
        //    {
        //        result.Code = -1;
        //        result.Message = ex.Message;
        //        throw;
        //    }
        //    return result;
        //}

        ///// <summary>
        ///// 修改用户信息
        ///// </summary>
        ///// <param name="userId">用户ID</param>
        ///// <returns>返回受影响的行数</returns>
        //[HttpGet]
        //public async Task<ApiResult<int>> UpdateUserInfo(int userId)
        //{
        //    ApiResult<int> result = new ApiResult<int>();
        //    try
        //    {
        //        result.Data = await _userInfoService.UpdateAsync(userId);
        //    }
        //    catch (Exception ex)
        //    {
        //        result.Code = -1;
        //        result.Message= ex.Message;
        //        throw;
        //    }
        //    return result;
        //}

        /// <summary>
        /// 删除用户信息
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>返回受影响的行数</returns>
        [HttpGet]
        public async Task<ApiResult<int>> DeleteUserInfo(int userId)
        {
            ApiResult<int> result = new ApiResult<int>();
            try
            {
                result.Data = await _userInfoService.DeletedAsync(userId);
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }

        ///// <summary>
        ///// 条件查询用户信息
        ///// </summary>
        ///// <param name="userName">用户名称</param>
        ///// <returns>返回用户信息</returns>
        //[HttpGet]
        //public async Task<ApiResult<List<UserInfo>>> GetUserInfoBy(string userName)
        //{
        //    ApiResult<List<UserInfo>> result = new ApiResult<List<UserInfo>>();
        //    try
        //    {
        //        result.Data = await _userInfoService.GetAllAsync(userName);
        //    }
        //    catch (Exception ex)
        //    {
        //        result.Code = -1;
        //        result.Message = ex.Message;
        //        throw;
        //    }
        //    return result;
        //}

        /// <summary>
        /// 反填用户信息
        /// </summary>
        /// <param name="userId">用户主键</param>
        /// <returns>反填用户信息</returns>
        [HttpGet]
        public async Task<ApiResult<UserInfo>> GetUserInfoById(int userId)
        {
            ApiResult<UserInfo> result = new ApiResult<UserInfo>();
            try
            {
                result.Data = await _userInfoService.GetModelAsync(userId);
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }

        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="userInfo">修改后的用户信息实体</param>
        /// <returns>返回受影响的行数</returns>
        [HttpPut]
        public async Task<ApiResult<int>> UpdateUserInfoAsync(UserInfo userInfo)
        {
            ApiResult<int> result = new ApiResult<int>();
            try
            {
                //用户名称重名判断
                //var res = await _userInfoService.GetAllAsync(userName: userInfo.UserName);
                //if (res.Count > 0)
                //{
                //    result.Code = -2;
                //}
                //else
                //{
                //    result.Data = await _userInfoService.UpdateUserInfoAsync(userInfo);
                //}          
                result.Data = await _userInfoService.UpdateUserInfoAsync(userInfo);
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }

        /// <summary>
        /// 获取用户ID和名称
        /// </summary>
        /// <param name="ids">多个部门ID</param>
        /// <returns>返回用户指定信息</returns>
        [HttpGet]
        public async Task<ApiResult<List<UserInfoDtoTwo>>> GetALLInfoAsyncTwo(string ids)
        {
            ApiResult<List<UserInfoDtoTwo>> result = new ApiResult<List<UserInfoDtoTwo>>();
            try
            {
                result.Data = await _userInfoService.GetALLInfoAsyncTwo(ids);
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }

        /// <summary>
        /// 添加用户信息---MediatR 中介者
        /// </summary>
        /// <param name="command">添加用户命令</param>
        /// <returns>返回受影响的行数</returns>
        [HttpPost]
        public async Task<ApiResult<int>> Create(UserInfoCreateCommand command)
        {
            ApiResult<int> result = new ApiResult<int>();
            try
            {
                var res = await _userInfoService.GetAllAsync(userName: command.UserName);
                if (res.Count > 0)
                {
                    result.Code = -2;
                }
                else
                {
                    result.Data = await _mediator.Send(command);
                }
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }

        /// <summary>
        /// 获取全部用户列表
        /// </summary>
        /// <param name="command">查询用户命令</param>
        /// <returns>返回全部用户列表</returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<ApiResult<PageUserInfoDto<UserInfoDto>>> Search(UserInfoSearchCommand command)
        {
            ApiResult<PageUserInfoDto<UserInfoDto>> result = new ApiResult<PageUserInfoDto<UserInfoDto>>();
            try
            {
                result.Data = await _mediator.Send(command);
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }

        /// <summary>
        /// 删除用户信息
        /// </summary>
        /// <param name="commad">删除用户命令</param>
        /// <returns>返回受影响的行数</returns>
        [HttpPost]
        public async Task<ApiResult<int>> Delete(UserInfoRemoveCommad commad)
        {
            ApiResult<int> result = new ApiResult<int>();
            try
            {
                result.Data = await _mediator.Send(commad);
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }

        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="command">修改用户命令</param>
        /// <returns>返回受影响的行数</returns>
        [HttpPut]
        public async Task<ApiResult<int>> Update(UserInfoUpdateCommand command)
        {
            ApiResult<int> result = new ApiResult<int>();
            try
            {        
                result.Data = await _mediator.Send(command);
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }

        /// <summary>
        /// 反填用户信息
        /// </summary>
        /// <param name="command">用户主键</param>
        /// <returns>反填用户信息</returns>
        [HttpPost]
        public async Task<ApiResult<UserInfo>> Find(UserInfoReverseFillingCommand command)
        {
            ApiResult<UserInfo> result = new ApiResult<UserInfo>();
            try
            {
                result.Data = await _mediator.Send(command);
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }

        /// <summary>
        /// 通过部门ID获取用户ID和名称
        /// </summary>
        /// <param name="command">多个部门ID</param>
        /// <returns>返回用户指定信息</returns>
        [HttpPost]
        public async Task<ApiResult<List<UserInfoDtoTwo>>> SearchInfo(UserInfoSearchInfoCommand command)
        {
            ApiResult<List<UserInfoDtoTwo>> result = new ApiResult<List<UserInfoDtoTwo>>();
            try
            {
                result.Data = await _mediator.Send(command);
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="command">用户信息</param>
        /// <returns>返回用户信息</returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<ApiResult<string>> UserLogin(UserInfoLoginCommand command)
        {
            ApiResult<string> result = new ApiResult<string>();

            var userId = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;//获取sub的值(userId)
            var roleId = HttpContext.User.FindFirst(ClaimTypes.Role)?.Value;//获取Role的值(roleId);

            try
            {
                var res = await _mediator.Send(command);
                if (res != null)
                {
                    result.Data = JwtNewString(res.UserId.ToString(),res.RoleId.ToString());
                }
                else
                {
                    result.Code = -2;
                    result.Message = "用户名或密码错误";
                }
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }

        /// <summary>
        /// 签发Token令牌
        /// </summary>
        /// <param name="userId">用户唯一标识</param>
        /// <param name="roleId">角色ID</param>
        /// <returns>返回Token令牌</returns>
        private string JwtNewString(string userId,string roleId)
        {
            //生成JWT
            //Header头部 选择签名算法
            var signingAlogorihm = SecurityAlgorithms.HmacSha256;
            //Payload 载荷 自定义数据 存储用户信息 ,这里存储用户ID
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub,userId),
                new Claim(ClaimTypes.Role,roleId),
                //new Claim(ClaimTypes.UserData,"测试")
            };
            //Signature 
            //取出私钥并以UTF8编码字节输出
            var secretByte = Encoding.UTF8.GetBytes(configuration["Authentication:SecretKey"]);
            //使用非对称算法对私钥进行加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            //使用HmacSha256来验证加密后的私钥生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, signingAlogorihm);
            //生成Token
            var Token = new JwtSecurityToken(
                issuer: configuration["Authentication:Issuer"], //发布者
                audience: configuration["Authentication:Audience"], //接收者
                claims: claims,                                     //存放的用户信息
                notBefore: DateTime.Now,                            //发布时间
                expires: DateTime.UtcNow.AddDays(1),                //过期时间
                signingCredentials                                 //数字签名
                );
            //生成字符串Token
            var TokenStr = new JwtSecurityTokenHandler().WriteToken(Token);
            return TokenStr;
        }

    }
}
